package org.baygo.view.api.listener;

import org.babygo.connect.NettyFileOperator;
import org.baygo.view.api.impl.MyViewOperator;
import org.baygo.view.api.listener.mycomponent.MyButton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;

public class ConnectedClientButtonActionListener extends MouseAdapter{
	private Logger log = LoggerFactory.getLogger(ConnectedClientButtonActionListener.class);

	private static NettyFileOperator fileServer = new NettyFileOperator();
	{
		NettyFileOperator.setViewOperator(MyViewOperator.getMyOperator());
	}
    private MyButton connectButton;
    private String ip;
    private String port;

    public static NettyFileOperator getFileServer() {
		return fileServer;
	}

	public static void setFileServer(NettyFileOperator fileServer) {
		ConnectedClientButtonActionListener.fileServer = fileServer;
	}

	public ConnectedClientButtonActionListener(MyButton connectButton, String ip, String port){
    	this.connectButton = connectButton;
    	this.ip = ip;
    	this.port = port;
    }

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getButton()==MouseEvent.BUTTON1 && e.getClickCount() == 2){
			doWork();
		}
	}

	public void doWork() {
		SwingWorker <String, Boolean> server = new SwingWorker<String, Boolean>(){

			@Override
			protected String doInBackground() throws Exception {
				log.info("发送文件");
				File f = MyViewOperator.getMyOperator().getFile();
				if (!f.isFile()){
					log.error("这不是一个有效文件");
				}
//				System.out.println(connectButton.getText());
//				String[] ipAndPort = connectButton.getText().split(":");
//				fileServer.sendFile(ipAndPort[0], ipAndPort[1], f);
				fileServer.sendFile(ip, port, f);
				return "发送文件结束";
			}

			@Override
			protected void process(List<Boolean> chunks) {
				log.info("process");
				for (Boolean result : chunks) {
					if (result==true){
//						logArea.append("远程连接成功!\n");
						connectButton.setBackground(Color.green);
						connectButton.turnGreen();
					}
					if (result == false){
//						logArea.append(String.format("到:%s-%s 的远程连接断开!\n", ip, port));
						connectButton.turnRed();
					}
				}
			}
		};
		server.execute();
	}
}